const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    list: [],
  },
  // lifetimes
  onLoad(options) {
    this.refresh()
  },
  onPullDownRefresh() {
    this.refresh()
  },
  onReachBottom() {
    this.page += 1
    this.setData({
      page: this.data.page + 1,
    })
    this.getList()
  },
  onShareAppMessage() {
    return {
      title: '来撸猫吧~',
    }
  },
  // methods
  /**
   * 获取列表数据
   */
  async getList(page = this.data.page) {
    const ret = await db.collection('Animal').limit(20).skip(page * 20).field ({
      name: true,
      age: true,
      cover_img: true,
      jueyu: true,
      lingyang: true,
      quchong_outer: true,
      quchong_inner: true,
    }).get()
    wx.stopPullDownRefresh()
    wx.hideToast()
    this.setData({
      list: [...this.data.list, ...this.format(ret.data)],
    })
    // console.log(this.data.list)
  },
  format(list) {
    return list.map(i => {
      i.id = i.sex ? (i.sex === 1 ? 'M' + i.id : 'G' + i.id) : 'X' + i.id
      i.quchong_outer_label = i.quchong_outer ? app.util.formatDate(i.quchong_outer, 'YY/MM/DD') :
        '未驱虫'
      i.quchong_inner_label = i.quchong_inner ? app.util.formatDate(i.quchong_inner, 'YY/MM/DD') :
        '未驱虫'
      i.lingyang_label = app.util.getLingyangLevelLabel(i.lingyang_level)
      i.jueyu_label = i.jueyu_status ? (i.jueyu_status === 1 ? '已绝育' : '未知') : '未绝育'
      return i
    })
  },
  /**
   * 刷新列表
   */
  refresh() {
    app.showToast('列表拉取...')
    this.setData({
      page: 0,
      list: [],
    })
    this.getList()
  },
})